package http

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"

	"daxin.my/test-netserver/api"
)

type HttpClient struct {
	serverAddress string
	state         int32 // 当前发送消息状态， 0. 正常 1. 错误 2. 慢
}

func InitHttpClient(httpServerAddress string) *HttpClient {
	log.Printf("Start Http Client, address: %s\n", httpServerAddress)

	return &HttpClient{
		serverAddress: httpServerAddress,
		state:         0,
	}
}

func (client *HttpClient) Request(param api.RequestParam) {
	url := fmt.Sprintf("http://%s/test?sleep=%d&respbyte=%d&statusCode=%d", client.serverAddress, param.Sleep, param.ResponseByteNum, param.StatusCode)
	contentType := "text/plain"
	bodyBytes := make([]byte, param.RequestByteNum)
	body := strings.NewReader(string(bodyBytes))

	startTime := time.Now()
	response, err := http.Post(url, contentType, body)
	if err != nil {
		log.Printf("Http Client Failed: %v\n", err)
		return
	}
	defer response.Body.Close()
	// 直到读出所有内容再结束
	result, _ := ioutil.ReadAll(response.Body)
	duration := time.Since(startTime)
	log.Printf("Http Client Success. request size = %d, response size = %d, statusCode = %d, duration %dms",
		body.Size(), len(result), response.StatusCode, duration.Milliseconds())
}

func (client *HttpClient) Visit() {
	requestParam := api.RequestParam{
		Sleep:           0,
		StatusCode:      200,
		RequestByteNum:  10,
		ResponseByteNum: 10,
	}

	switch client.state {
	case 1:
		requestParam.StatusCode = 400
		client.state = 2
	case 2:
		requestParam.Sleep = 500
		client.state = 0
	default:
		client.state = 1
	}
	client.Request(requestParam)
}

func (client *HttpClient) Close() {
}
